
package com.example.xxcjgl.ui.screens

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Check
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Card
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.example.xxcjgl.data.models.Resource
import com.example.xxcjgl.data.models.Student
import com.example.xxcjgl.viewmodel.StudentViewModel
import java.text.SimpleDateFormat
import java.util.Date
import androidx.compose.runtime.collectAsState

// AddScoreScreen.kt
@Composable
fun AddScoreScreen(
    onBack: () -> Unit,
    viewModel: StudentViewModel = hiltViewModel()
) {
    var selectedStudent by remember { mutableStateOf<Student?>(null) }
    var mathScore by remember { mutableStateOf("") }
    var chineseScore by remember { mutableStateOf("") }
    var useEncryption by remember { mutableStateOf(false) }
    var encryptionKey by remember { mutableStateOf("") }
    var showStudentDialog by remember { mutableStateOf(false) }

    val students by viewModel.students.collectAsState()
    val addScoreState by viewModel.addScoreState.collectAsState()

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("录入成绩") },
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(Icons.Default.ArrowBack, contentDescription = "返回")
                    }
                },
                actions = {
                    IconButton(onClick = {
                        if (selectedStudent == null || mathScore.isBlank() || chineseScore.isBlank()) {
                            return@IconButton
                        }

                        val math = mathScore.toFloatOrNull()
                        val chinese = chineseScore.toFloatOrNull()

                        if (math == null || chinese == null) {
                            return@IconButton
                        }

                        viewModel.addScore(
                            Student(
                                xscjb_xh = selectedStudent!!.xscjb_xh,
                                xscjb_mc = selectedStudent!!.xscjb_mc,
                                xscjb_xb = selectedStudent!!.xscjb_xb,
                                xscjb_sxcj = math,
                                xscjb_ywcj = chinese,
                                xscjb_csrrq = SimpleDateFormat("yyyy-MM-dd").format(Date()),
                                xscjb_jmbz = if (useEncryption) 1 else 0,
                                xdcjb_jmmy = if (useEncryption) encryptionKey else null
                            )
                        )
                    }) {
                        Icon(Icons.Default.Check, contentDescription = "保存")
                    }
                }
            )
        }
    ) { padding ->
        Column(
            modifier = Modifier
                .padding(padding)
                .fillMaxSize()
                .padding(16.dp)
        ) {
            // 学生选择
            OutlinedTextField(
                value = selectedStudent?.xscjb_mc ?: "",
                onValueChange = { },
                label = { Text("选择学生") },
                readOnly = true,
                modifier = Modifier
                    .fillMaxWidth()
                    .clickable { showStudentDialog = true }
            )

            Spacer(modifier = Modifier.height(16.dp))

            OutlinedTextField(
                value = mathScore,
                onValueChange = { mathScore = it },
                label = { Text("数学成绩") },
                modifier = Modifier.fillMaxWidth()
            )

            Spacer(modifier = Modifier.height(16.dp))

            OutlinedTextField(
                value = chineseScore,
                onValueChange = { chineseScore = it },
                label = { Text("语文成绩") },
                modifier = Modifier.fillMaxWidth()
            )

            Spacer(modifier = Modifier.height(16.dp))

            Row(verticalAlignment = Alignment.CenterVertically) {
                Checkbox(
                    checked = useEncryption,
                    onCheckedChange = { useEncryption = it }
                )
                Text("加密成绩")
            }

            if (useEncryption) {
                Spacer(modifier = Modifier.height(16.dp))
                OutlinedTextField(
                    value = encryptionKey,
                    onValueChange = { encryptionKey = it },
                    label = { Text("加密密钥") },
                    modifier = Modifier.fillMaxWidth()
                )
            }

            // 学生选择对话框
            if (showStudentDialog) {
                AlertDialog(
                    onDismissRequest = { showStudentDialog = false },
                    title = { Text("选择学生") },
                    text = {
                        LazyColumn {
                            items(students.data ?: emptyList()) { student ->
                                Card(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(4.dp)
                                        .clickable {
                                            selectedStudent = student
                                            showStudentDialog = false
                                        }
                                ) {
                                    Text(
                                        text = student.xscjb_mc,
                                        modifier = Modifier.padding(16.dp)
                                    )
                                }
                            }
                        }
                    },
                    confirmButton = {
                        TextButton(onClick = { showStudentDialog = false }) {
                            Text("取消")
                        }
                    }
                )
            }

            // 处理保存结果
            when (addScoreState) {
                is Resource.Success -> {
                    LaunchedEffect(Unit) {
                        onBack()
                    }
                }
                is Resource.Error -> {
                    val errorState = addScoreState as Resource.Error<Unit>
                    Text(
                        text = errorState.message,
                        color = Color.Red,
                        modifier = Modifier.padding(top = 16.dp)
                    )
                }
                is Resource.Loading -> {
                    CircularProgressIndicator(modifier = Modifier.padding(top = 16.dp))
                }
                else -> {}
            }

        }
    }
}